package com.example.provider.config;

import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.example.provider.config.util.HttpContextHeaderHolder;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.Server;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class CustomRule extends AbstractLoadBalancerRule {
    private AtomicInteger nextServerCyclicCounter = new AtomicInteger(0);
    @Override
    public Server choose(Object key) {
        // 获取所有可用的服务实例
        List<Server> servers = getLoadBalancer().getAllServers();

        if (CollectionUtils.isEmpty(servers)) {
            return null;
        }

        // 筛选出符合条件的服务实例
        List<Server> filteredServers = servers.stream()
                .filter(server -> {
                    // 这里可以根据需要的条件进行筛选
                    // 假设有 metadata，可以通过其他方式获取
                    // 例如，检查 server 的某个属性
                    return checkServerCondition(server);
                })
                .collect(Collectors.toList());

        List<Server> result = filteredServers.isEmpty() ? servers : filteredServers;

        /// 轮询逻辑
        int index = nextServerCyclicCounter.getAndIncrement() % result.size();
        return result.get(index);
    }

    // 实现筛选条件，例如检查 metadata
    private boolean checkServerCondition(Server server) {
        try {
            NacosServer nacosServer = (NacosServer) server;
            Map<String, String> metadata = nacosServer.getMetadata();
            Map<String, Object> headers = HttpContextHeaderHolder.get();
            System.out.println("metadata = " + metadata);
            System.out.println("headers = " + headers);
            if (headers.containsKey("version")) {
                return metadata.get("version").equals(headers.get("version"));
            }
        } catch (Exception e) {
            return false;
        }

        return false; // 返回 true，表示所有的实例都通过; 返回false,实例不通过
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }
}